import {
  selectAddressLibList,
  checkAddress,
  addressLibOperate,
  addressLibDetail,
} from '@/services/addressLib';
import prompt from '@/components/Prompt';

export default {
  namespace: 'addressLib',

  state: {
    addressLibList: {}, // 地址库列表
    addressLibDetail: {}, // 地址库详情
    formValues: {},
  },

  effects: {
    /**
     * 查询地址库列表
     */
    *selectAddressLibList({ payload }, { call, put }) {
      const response = yield call(selectAddressLibList, payload);
      const { code, data } = response;
      if (code !== 0) return;
      const { list, pageSize, total, pageNum } = data;
      yield put({
        type: 'saveAddressLibList',
        payload: {
          addressLibList: {
            pagination: {
              current: pageNum,
              pageSize,
              total,
            },
            list,
          },
        },
      });
    },
    /**
     * 新增编辑地址库
     */
    *addressLibOperate({ payload, callback }, { call, put }) {
      const response = yield call(addressLibOperate, payload);
      const { code, data, message } = response;
      const content = payload.id ? `编辑${message}` : `新增${message}`;
      if (code !== 0) return;
      prompt({ content });
      if (callback) callback(data);
    },
    /**
     * 审核地址
     */
    *checkAddress({ payload, callback }, { call, put }) {
      const response = yield call(checkAddress, payload);
      const { code, message } = response;
      if (code !== 0) return;
      prompt({ content: `审核${message}!` });
      if (callback) callback(true);
    },
    /**
     * 地址库详情
     */
    *addressLibDetail({ payload, callback }, { call, put }) {
      const response = yield call(addressLibDetail, payload);
      const { code, data, message } = response;
      if (code !== 0) return;
      yield put({
        type: 'saveAddressLibDetail',
        payload: {
          addressLibDetail: { [payload.id]: data },
        },
      });
      if (callback) callback(data);
    },
    /**
     * 设置表单参数
     */
    *allValus({ payload }, { call, put }) {
      yield put({
        type: 'saveAllValus',
        payload,
      });
    },
  },

  reducers: {
    // 地址库列表
    saveAddressLibList(state, { payload }) {
      return {
        ...state,
        addressLibList: payload.addressLibList,
      };
    },
    // 地址库详情
    saveAddressLibDetail(state, { payload }) {
      return {
        ...state,
        addressLibDetail: { ...state.addressLibDetail, ...payload.addressLibDetail },
      };
    },
    //设置表单参数
    saveAllValus(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
